//
//  ScoreReportPageViewController.m
//  ActiveDeck
//
//  Created by Michael Cohen on 9/8/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ScoreReportPageViewController.h"
#import "PageViewController.h"
#import "AD_Page.h"
#import "scoreReportQuestion.h"

#define DEFAULT_CELL_HEIGHT 120

@implementation ScoreReportPageViewController

@synthesize BG_Image, scoreTableView, allPages, questionRows, scoreLabel; 


int selectedIndex = -1;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}*/



- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    // Do any additional setup after loading the view from its nib.
    BG_Image.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:pageOB.imageBG]];
    scoreTableView.tableFooterView.hidden = YES;
    scoreTableView.tableHeaderView.hidden = YES;
    
    [self loadReport];
    
    [super viewDidLoad];
}


- (void)loadReport{
    float totalQuestions = 0.0f;
    int questionsHeight = 0;
    float numberAnsweredCorrectly = 0.0f; 
    
    for(AD_Page *p in allPages){
        
        for(NSString *scQ in pageOB.mut_Arr_ScoreReportQuestions){  
            if ([scQ intValue] == p.pageID){                
                if(p.grade.hasInstantFeedback){
                    questionsHeight++;
                }
            }
        }
    }
    
    
    [scoreTableView setContentSize:CGSizeMake(scoreTableView.frame.size.width - 20, questionsHeight * 150)];
    
    questionRows = [[NSMutableArray alloc]initWithCapacity:[allPages count]];
    
    int qNumber = 0;    
    for(AD_Page *p in allPages){
        for(NSString *scQ in pageOB.mut_Arr_ScoreReportQuestions){  
            if ([scQ intValue] == p.pageID){    
                if(p.grade.hasInstantFeedback){
                    NSString *correctAnswer = p.grade.question.correctAnswerText;
                    NSString *qText = [NSString stringWithFormat:@"%i. %@", qNumber+1, p.grade.question.questionText];
                    NSMutableString *submittedAnswer = [[NSMutableString alloc] init];
                    if([p.pageType isEqualToString:@"MultipleChoiceQuestion"] || [p.pageType isEqualToString:@"ShortAnswerQuestion"]){
                        totalQuestions++;
                        if(p.grade.question.submittedAnswerText != nil){
                            [submittedAnswer appendString:p.grade.question.submittedAnswerText];
                        } else {
                            [submittedAnswer appendString:@""];
                        }                
                    } 
                    if ([p.pageType isEqualToString:@"Categories"]){
                        totalQuestions += [p.grade.question.possibleWords count];
                        if ([p.grade.question.possibleCategories count] > 0) {
                            [submittedAnswer appendString:@"\n"];
                        }
                        for (id catID in p.grade.question.possibleCategories){
                            NSArray *catWords = [p.grade.question.submittedCategories allKeysForObject:catID];
                            
                            [submittedAnswer appendFormat:@"%@(", [p.grade.question.possibleCategories objectForKey:catID]];
                            
                            for (id submittedWordID in catWords){
                                for (id wordID in p.grade.question.possibleWords){
                                    if ([wordID intValue] == [submittedWordID intValue]) {
                                        [submittedAnswer appendFormat:@"%@, ", [p.grade.question.possibleWords objectForKey:wordID]];
                                    }
                                }                             
                            }   
                            
                            if([submittedAnswer hasSuffix:@", "]){                                    
                                NSRange endRange = NSMakeRange([submittedAnswer length]-2, 2);
                                [submittedAnswer replaceCharactersInRange:endRange withString:@""];                                    
                            }
                            
                            [submittedAnswer appendString:@")\n"];
                        }
                        
                        if([submittedAnswer hasSuffix:@"\n"]){
                            
                            NSRange endRange = NSMakeRange([submittedAnswer length]-1, 1);
                            [submittedAnswer replaceCharactersInRange:endRange withString:@""];
                            
                        }
                    }
                    
                    
                    scoreReportQuestion *question = [[scoreReportQuestion alloc] init];
                    
                    
                    
                    question.questionLabel.text = qText;                     
                    [question.questionLabel setLineBreakMode:UILineBreakModeTailTruncation];
                    [self setLabelSize:question.questionLabel withMaxHeight:25]; 
                    
                    question.correctAnswerLabel.text = [[NSString alloc] initWithFormat:@"Correct Answer: %@", correctAnswer];
                    question.yourAnswerLabel.text = [[NSString alloc] initWithFormat:@"Your Answer: %@", submittedAnswer];
                    
                    NSLog(@"QLabel Height:%f, # of Lines: %d", question.questionLabel.frame.size.height, question.questionLabel.numberOfLines);

                    
                    question.tag = qNumber + 100;
                    UIImage *correctImage;
                    if (p.grade.hasAnsweredCorrectly) {
                        numberAnsweredCorrectly++;
                        correctImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"icon_lg_check" ofType:@"png"]];                
                    } else {
                        correctImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"icon_lg_x" ofType:@"png"]];
                    }
                    [question.isCorrectImage setImage:correctImage];
                    question.frame = CGRectMake(0, (DEFAULT_CELL_HEIGHT*qNumber), BG_Image.frame.size.width, DEFAULT_CELL_HEIGHT);
                    if(qNumber % 2 == 0){
                        question.contentView.backgroundColor = [[UIColor alloc] initWithRed:236.0f/255.0f green:244.0f/255.0f blue:247.0f/255.0f alpha:1];               
                    } else {
                        question.contentView.backgroundColor = [[UIColor alloc] initWithRed:1.0 green:1.0 blue:1.0 alpha:1];                        
                    }
                    
                    CGRect newFrame = question.contentView.frame;
                    newFrame.size.height = question.frame.size.height;
                    [question.contentView setFrame:newFrame];
                    
                    qNumber++;
                    [questionRows addObject:question];
                    
                    NSLog(@"QLabel: X: %f, Y: %f", question.questionLabel.frame.origin.x, question.questionLabel.frame.origin.y);
                    NSLog(@"CALabel: X: %f, Y: %f", question.correctAnswerLabel.frame.origin.x, question.correctAnswerLabel.frame.origin.y);
                    NSLog(@"YALabel: X: %f, Y: %f", question.yourAnswerLabel.frame.origin.x, question.yourAnswerLabel.frame.origin.y);
                    
                    [submittedAnswer release];
                }   
            }
        }
    }
    
    if(totalQuestions > 0){
        scoreLabel.text = [NSString stringWithFormat:@"%.0f%%", (numberAnsweredCorrectly/totalQuestions)*100.0f];
    } else {
        scoreLabel.text = @"0%";
    }
    
    if(isForPDF){
        [self expandAllCells];
    }
}

- (void)expandAllCells{
    for(scoreReportQuestion *q in questionRows){
        
        CGSize answerConstraint = CGSizeMake(340, 20000.0f);
        CGSize qConstraint = CGSizeMake(704, 20000.0f);
        
        
        CGSize caSize = [q.correctAnswerLabel.text sizeWithFont:[UIFont systemFontOfSize:19.0f] constrainedToSize:answerConstraint];
        CGSize yaSize = [q.yourAnswerLabel.text sizeWithFont:[UIFont systemFontOfSize:19.0f] constrainedToSize:answerConstraint];
        CGSize qSize = [q.questionLabel.text sizeWithFont:[UIFont systemFontOfSize:19.0f] constrainedToSize:qConstraint];
        
        if(caSize.height > q.initialCALabelHeight || yaSize.height > q.initialYALabelHeight || (qSize.height > q.initialQLabelHeight || qSize.width > q.questionLabel.bounds.size.width)){    
            
            CGRect newFrame;
            newFrame = CGRectMake(q.frame.origin.x, q.frame.origin.y, q.frame.size.width, DEFAULT_CELL_HEIGHT + (MAX(caSize.height, yaSize.height)) + (q.questionLabel.frame.size.height - q.initialQLabelHeight));
            
            [q setFrame:newFrame];
            
            [self expandCell:q correctAnswerLabelSize:caSize yourAnswerLabelSize:yaSize questionLabelSize:qSize];
            
        } 
    }
}

-(void)expandCell:(scoreReportQuestion*)q correctAnswerLabelSize:(CGSize)caSize yourAnswerLabelSize:(CGSize)yaSize questionLabelSize:(CGSize)qSize{
    [self setLabelSize:q.questionLabel withMaxHeight:9999];
    
    if(q.questionLabel.frame.size.height > q.initialQLabelHeight){                
        [self setLabelSize:q.correctAnswerLabel withMaxHeight:9999 andYPos:q.questionLabel.frame.size.height + (q.correctAnswerLabel.frame.origin.y - q.questionLabel.frame.origin.y)];                        
        [self setLabelSize:q.yourAnswerLabel withMaxHeight:9999 andYPos:q.questionLabel.frame.size.height + (q.yourAnswerLabel.frame.origin.y - q.questionLabel.frame.origin.y)];
    } else {
        [self setLabelSize:q.correctAnswerLabel withMaxHeight:9999];                        
        [self setLabelSize:q.yourAnswerLabel withMaxHeight:9999];
    }
    
    q.frame = CGRectMake(q.frame.origin.x, q.frame.origin.y, q.frame.size.width, DEFAULT_CELL_HEIGHT + (MAX(caSize.height, yaSize.height)) + (q.questionLabel.frame.size.height - q.initialQLabelHeight)); 
}

- (void)setLabelSize:(UILabel*)label withMaxHeight:(int)maxHeight{
    [self setLabelSize:label withMaxHeight:(int)maxHeight andYPos:label.frame.origin.y];
}

- (void)setLabelSize:(UILabel *)label withMaxHeight:(int)maxHeight andYPos:(int)yPos{
    CGSize maxLabelSize = CGSizeMake(label.frame.size.width, maxHeight);
    
    CGSize expectedLabelSize = [label.text sizeWithFont:label.font constrainedToSize:maxLabelSize lineBreakMode:label.lineBreakMode];
    
    CGRect newFrame = label.frame;
    newFrame.size.height = expectedLabelSize.height;
    newFrame.origin.y = yPos;
    [label setFrame:newFrame];

}

#pragma mark - UITableViewDelegate methods

-(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    scoreReportQuestion *question = [questionRows objectAtIndex:indexPath.row];
    
    CGSize answerConstraint = CGSizeMake(340, 20000.0f);
    
    CGSize caSize = [question.correctAnswerLabel.text sizeWithFont:[UIFont systemFontOfSize:19.0f] constrainedToSize:answerConstraint];
    CGSize yaSize = [question.yourAnswerLabel.text sizeWithFont:[UIFont systemFontOfSize:19.0f] constrainedToSize:answerConstraint];
    if(selectedIndex == indexPath.row || isForPDF){  
        if (caSize.height > 55 || yaSize.height > 55 || (question.questionLabel.frame.size.height > question.initialQLabelHeight)){
            return DEFAULT_CELL_HEIGHT + (MAX(caSize.height, yaSize.height)) + (question.questionLabel.frame.size.height - question.initialQLabelHeight);
        } 
    }
    
    return DEFAULT_CELL_HEIGHT;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    scoreReportQuestion *question = [questionRows objectAtIndex:indexPath.row];
    
    CGSize sizeConstraint = CGSizeMake(704, 20000.0f);
    
    CGSize caSize = [question.correctAnswerLabel.text sizeWithFont:[UIFont systemFontOfSize:19.0f] constrainedToSize:sizeConstraint];
    CGSize yaSize = [question.yourAnswerLabel.text sizeWithFont:[UIFont systemFontOfSize:19.0f] constrainedToSize:sizeConstraint];
    CGSize qSize = [question.questionLabel.text sizeWithFont:[UIFont systemFontOfSize:19.0f] constrainedToSize:sizeConstraint];
        
    if(selectedIndex == indexPath.row){
        
        if(caSize.height > question.initialCALabelHeight){
            [self setLabelSize:question.correctAnswerLabel withMaxHeight:question.initialCALabelHeight andYPos:question.initialCALabelY];
        }
        
        if (yaSize.height > question.initialYALabelHeight) {
            [self setLabelSize:question.yourAnswerLabel withMaxHeight:question.initialYALabelHeight andYPos:question.initialYALabelY];
        }
        
        if (qSize.height > question.initialQLabelHeight || qSize.width > question.questionLabel.bounds.size.width) {
            [self setLabelSize:question.questionLabel withMaxHeight:question.initialQLabelHeight];
            [self setLabelSize:question.yourAnswerLabel withMaxHeight:question.initialYALabelHeight andYPos:question.initialYALabelY];
            [self setLabelSize:question.correctAnswerLabel withMaxHeight:question.initialCALabelHeight andYPos:question.initialCALabelY];
        }
        
        selectedIndex = -1;
        [scoreTableView beginUpdates];
        [scoreTableView reloadData];
        [scoreTableView endUpdates];
        
        return;
    }
    
    if(selectedIndex >= 0){
        scoreReportQuestion *q = [questionRows objectAtIndex:selectedIndex];
        
        [self setLabelSize:q.questionLabel withMaxHeight:q.initialQLabelHeight];
        [self setLabelSize:q.correctAnswerLabel withMaxHeight:q.initialCALabelHeight andYPos:question.initialCALabelY];                        
        [self setLabelSize:q.yourAnswerLabel withMaxHeight:q.initialYALabelHeight andYPos:question.initialYALabelY];       
    }    
    
    selectedIndex = indexPath.row;
    
    if(caSize.height > question.initialCALabelHeight || yaSize.height > question.initialYALabelHeight || (qSize.height > question.initialQLabelHeight || qSize.width > question.questionLabel.bounds.size.width)){
        NSLog(@"Score Report Selected Row Index: %d", selectedIndex);
        if(selectedIndex >= 0){
            [self expandCell:question correctAnswerLabelSize:caSize yourAnswerLabelSize:yaSize questionLabelSize:qSize];
        }
    } else {
        if (qSize.height > question.initialQLabelHeight) {
            [self truncateLabel:question.questionLabel];
        }
        
        if (caSize.height > question.initialCALabelHeight) {
            [self truncateLabel:question.correctAnswerLabel];
        }
        
        if (yaSize.height > question.initialYALabelHeight) {
            [self truncateLabel:question.yourAnswerLabel];
        }
    }  
    
    [scoreTableView beginUpdates];
    [scoreTableView reloadData];
    [scoreTableView endUpdates];
}

-(void)truncateLabel:(UILabel*)label{
    [label setNumberOfLines:1];
    [label setClipsToBounds:YES];
    [label setLineBreakMode:UILineBreakModeTailTruncation];
}

#pragma mark - UITableViewDataSource methods

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
    return [questionRows count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    
    return [questionRows objectAtIndex:indexPath.row];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc
{
    [BG_Image release];
    [super dealloc];
}

@end
